package cn.ac.iie.di.ban.data.exchange.runner.master.helper.utils;

import cn.ac.iie.di.ban.data.exchange.runner.commons.protocol.StatusEnum;
import cn.ac.iie.di.ban.data.exchange.runner.commons.protocol.proxy.DataProxyResponse;
import cn.ac.iie.di.ban.data.exchange.runner.master.ParserFastJson;
import cn.ac.iie.di.ban.data.exchange.runner.master.helper.HttpHelper.HttpHelper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Black-Laptop
 */
public class utils {
    static Logger logger = Logger.getLogger(utils.class);


    public Boolean checkTaskFull(String uid, List<String> websiteUrls, List<String> metadataUrls, int queryMaxNum, String type) throws Exception {
        String uids;
        JSONObject uidResponse = getUidsInAgency(websiteUrls, uid);
        JSONObject result = uidResponse.getJSONObject("result");
        if ("success".equals(uidResponse.getString("status"))) {
            uids = result.getString("uids");
            uids = uids.replace("[", "(").replace("]", ")");
        } else {
            logger.error(result);
            throw new Exception(result.toJSONString());

        }

        int queryTaskNum;
        JSONObject queryTaskResponse = getQueryTaskNum(metadataUrls, uids, type);
        if ("succeeded".equals(queryTaskResponse.getString("status"))) {
            JSONObject queryTaskData = JSONObject.parseObject(String.valueOf(queryTaskResponse.getJSONArray("data").get(0)));
            queryTaskNum = queryTaskData.getIntValue("count(*)");
        } else {
            logger.error(queryTaskResponse.getString("detail"));
            throw new Exception(queryTaskResponse.getString("detail"));
        }
        return queryTaskNum > queryMaxNum;
    }

    private JSONObject getUidsInAgency(List<String> urls, String uid) throws Exception {
        // "http://192.168.11.187:8000/get_all_uid/"
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("uid", uid));

        String errorMsg = "";
        String response = null;

        for (String url : urls) {
            try {
                response = HttpHelper.httpPost(url, params);
                break;
            } catch (Exception e) {
                errorMsg = ExceptionUtils.getFullStackTrace(e);
            }
        }

        if (!("".equals(errorMsg))) {
            logger.error(errorMsg);
            throw new Exception(errorMsg);
        }

        return JSONObject.parseObject(response);
    }

    private JSONObject getQueryTaskNum(List<String> urls, String uids, String type) throws Exception {
        // http://192.168.11.96:10240/data/
        long timestampNow = System.currentTimeMillis() / 1000;
        long timestampStart = timestampNow - 24 * 60 * 60;
        uids = uids.replace("L", "");
        String sql = "select count(*) from de_metadata.request where start>" + timestampStart + " and type in " + type + " and uid in " + uids;
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("scope", "audit"));
        params.add(new BasicNameValuePair("opration", "search"));
        params.add(new BasicNameValuePair("content", ""));
        params.add(new BasicNameValuePair("condition", sql));

        String errorMsg = "";
        String response = null;
        for (String url : urls) {
            try {
                response = HttpHelper.httpPost(url, params);
            } catch (Exception e) {
                errorMsg = ExceptionUtils.getFullStackTrace(e);
            }
        }

        if (!("".equals(errorMsg))) {
            logger.error(errorMsg);
            throw new Exception(errorMsg);
        }

        return JSONObject.parseObject(response);
    }

    public Boolean sendRequestNew(String reqId, int scope, String sql, String status, String detail, String taskResult, String uniqSql, String taskId, String uniqKey, String uid, List<String> metadataUrls) throws Exception {
        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("scope", "request");
        requestMap.put("opration", "new");
        requestMap.put("condition", "");
        Map<String, Object> initRequestContent = new HashMap<>();
        initRequestContent.put("req_id", reqId);
        initRequestContent.put("type", scope);
        initRequestContent.put("usql", sql);
        initRequestContent.put("status", status);
        initRequestContent.put("detail", detail);
        initRequestContent.put("result", taskResult);
        initRequestContent.put("uniq_seq", uniqSql);
        initRequestContent.put("task_id", taskId);
        initRequestContent.put("rgroup", uniqKey);
        initRequestContent.put("uid", uid);
        initRequestContent.put("start", System.currentTimeMillis() / 1000);
        requestMap.put("content", new JSONObject(initRequestContent).toString());
        String queryRequestGroupNameReturn = ParserFastJson.requestMetadata(metadataUrls, requestMap);
        logger.info(uniqKey + " to confirm whether this groupname " + uniqKey + " has been used, and return " + queryRequestGroupNameReturn);
        boolean queryRequestGroupNameFlag = ParserFastJson.returnError(queryRequestGroupNameReturn);
        if (queryRequestGroupNameFlag) {
            throw new Exception(queryRequestGroupNameReturn);
        }

        return true;
    }
}
